package com.qiguliuxing.dts.admin.controller;

import com.github.pagehelper.PageInfo;
import com.qiguliuxing.dts.admin.annotation.RequiresPermissionsDesc;
import com.qiguliuxing.dts.admin.service.AdminBrandService;
import com.qiguliuxing.dts.admin.vo.DtsBrandVo;
import com.qiguliuxing.dts.common.constant.ApiAdminConsts;
import com.qiguliuxing.dts.common.constant.LogParamsConsts;
import com.qiguliuxing.dts.common.util.ResponseUtils;
import com.qiguliuxing.dts.core.annotation.aoplog.WebLog;
import com.qiguliuxing.dts.core.validator.Order;
import com.qiguliuxing.dts.core.validator.Sort;
import com.qiguliuxing.dts.db.domain.DtsBrandMerchant;
import com.qiguliuxing.dts.db.domain.DtsCategory;
import com.qiguliuxing.dts.service.base.DtsBrandService;
import com.qiguliuxing.dts.service.base.DtsCategoryService;
import com.qiguliuxing.dts.service.qcode.QCodeService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.validation.constraints.NotNull;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/admin/brand")
@Validated
@Api(tags = ApiAdminConsts.Brand.PARENT)
public class AdminBrandController {
	private static final Logger logger = LoggerFactory.getLogger(AdminBrandController.class);

	@Autowired
	private DtsBrandService brandService;
	
	@Autowired
	private DtsCategoryService categoryService;
	
	@Autowired
	private AdminBrandService adminBrandService;
	
	@Autowired
	private QCodeService qCodeService;

	@GetMapping("/list")
	@RequiresPermissions("admin:brand:list")
	@RequiresPermissionsDesc(menu = { "商场管理", "品牌管理" }, button = "查询")
	@ApiOperation(value = ApiAdminConsts.Brand.LIST)
	@WebLog(description = ApiAdminConsts.Brand.LIST, excludes = {LogParamsConsts.RESPONSE})
	public Object list(@ApiParam(value = "id") String id,
					   @ApiParam(value = "name") String name,
					   @ApiParam(value = "页码",defaultValue = "1") @RequestParam(defaultValue = "1") Integer page,
					   @ApiParam(value = "分页大小",defaultValue = "10") @RequestParam(defaultValue = "10") Integer limit,
					   @ApiParam(value = "排序字段",defaultValue = "add_time") @Sort @RequestParam(defaultValue = "add_time") String sort,
					   @ApiParam(value = "排序规则",defaultValue = "desc") @Order @RequestParam(defaultValue = "desc") String order) {

		List<DtsBrandMerchant> brandList = brandService.querySelective(id, name, page, limit, sort, order);
		long total = PageInfo.of(brandList).getTotal();
		Map<String, Object> data = new HashMap<>();
		
		List<DtsBrandVo> brandVoList = new ArrayList<DtsBrandVo> (brandList == null ? 0 : brandList.size());
		for(DtsBrandMerchant brand : brandList) {
			DtsBrandVo brandVo = new DtsBrandVo();
			BeanUtils.copyProperties(brand, brandVo);//对象属性的复制
			// 用于展示商品归属的类目（页面级联下拉控件数据展示）
			Integer categoryId = brand.getDefaultCategoryId();
			DtsCategory category = categoryService.findById(categoryId);
			Integer[] categoryIds = new Integer[] {};
			if (category != null) {
				Integer parentCategoryId = category.getPid();
				categoryIds = new Integer[] { parentCategoryId, categoryId };
				brandVo.setCategoryIds(categoryIds);
			}
			brandVoList.add(brandVo);
		}
		
		data.put("total", total);
		data.put("items", brandVoList);

		return ResponseUtils.ok(data);
	}

	@PostMapping("/create")
	@RequiresPermissions("admin:brand:create")
	@RequiresPermissionsDesc(menu = { "商场管理", "品牌管理" }, button = "添加")
	@ApiOperation(value = ApiAdminConsts.Brand.CREATE)
	@WebLog(description = ApiAdminConsts.Brand.CREATE, persistence = true)
	public Object create(@RequestBody DtsBrandMerchant brand) {
		if (!brandService.validate(brand)) {
			return ResponseUtils.badArgument();
		}
		
		try {
			//生成店铺的分享URL
			String defaultCategory = brandService.getBrandCategory(brand.getDefaultCategoryId());
			String shareUrl = qCodeService.createBrandImage(null,brand.getId(), brand.getPicUrl(), brand.getName(),defaultCategory);
			brand.setShareUrl(shareUrl);
		} catch (Exception e) {
			logger.error("生成品牌商铺分享图URL出错：{}",e.getMessage());
			e.printStackTrace();
		}
		
		brandService.add(brand);
		return ResponseUtils.ok(brand);
	}

	@GetMapping("/read")
	@RequiresPermissions("admin:brand:read")
	@RequiresPermissionsDesc(menu = { "商场管理", "品牌管理" }, button = "详情")
	@ApiOperation(value = ApiAdminConsts.Brand.READ)
	@WebLog(description = ApiAdminConsts.Brand.READ)
	public Object read(@ApiParam(value = "品牌id") @NotNull Integer id) {
		DtsBrandMerchant brand = brandService.findById(id);
		return ResponseUtils.ok(brand);
	}

	@PostMapping("/update")
	@RequiresPermissions("admin:brand:update")
	@RequiresPermissionsDesc(menu = { "商场管理", "品牌管理" }, button = "编辑")
	@ApiOperation(value = ApiAdminConsts.Brand.UPDATE)
	@WebLog(description = ApiAdminConsts.Brand.UPDATE, persistence = true)
	public Object update(@RequestBody DtsBrandMerchant brand) {
		if (!brandService.validate(brand)) {
			return ResponseUtils.badArgument();
		}
		try {
			//生成店铺的分享URL
			String defaultCategory = brandService.getBrandCategory(brand.getDefaultCategoryId());
			String shareUrl = qCodeService.createBrandImage(null,brand.getId(), brand.getPicUrl(), brand.getName(),defaultCategory);
			brand.setShareUrl(shareUrl);
		} catch (Exception e) {
			logger.error("生成品牌商铺分享图URL出错：{}",e.getMessage());
			e.printStackTrace();
		}
		if (brandService.updateById(brand) == 0) {
			logger.error("商场管理->品牌管理->编辑 失败，更新数据失败！");
			return ResponseUtils.updatedDataFailed();
		}
		return ResponseUtils.ok(brand);
	}

	@PostMapping("/delete")
	@RequiresPermissions("admin:brand:delete")
	@RequiresPermissionsDesc(menu = { "商场管理", "品牌管理" }, button = "删除")
	@ApiOperation(value = ApiAdminConsts.Brand.DELETE)
	@WebLog(description = ApiAdminConsts.Brand.DELETE, persistence = true)
	public Object delete(@RequestBody DtsBrandMerchant brand) {
		Integer id = brand.getId();
		if (id == null) {
			return ResponseUtils.badArgument();
		}
		brandService.deleteById(id);
		return ResponseUtils.ok();
	}

	@GetMapping("/catAndAdmin")
	@ApiOperation(value = ApiAdminConsts.Brand.CAT_AND_ADMIN)
	@WebLog(description = ApiAdminConsts.Brand.CAT_AND_ADMIN, persistence = true)
	public Object catAndAdmin() {
		return adminBrandService.catAndAdmin();
	}
}
